<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 17-12-20
 * Time: 下午4:26
 */

namespace common\components\gps;

use wodrow\yii\rest\ApiException;
use yii\base\ErrorException;
use yii\helpers\ArrayHelper;
use yii\httpclient\Client;

class JinLiMing extends Gps implements Api
{
    const PRE_SIGN = '353';
    const NAME = 'jin_li_ming';
    const NOTE = '金立铭'; // http://www.jlmgps.com/Skins/JlmGps/?locale=cn&back=true
    const LOGIN_TYPE_COMPANY = "ENTERPRISE";
    const LOGIN_TYPE_USER = "USER";
    const LANGUAGE_EN = "en";
    const LANGUAGE_CN = "cn";
    const MAP_TYPE_GOOGLE = "GOOGLECN";
    const MAP_TYPE_BAIDU = "BAIDU";
    const MAP_TYPE_GAODE = "GAODE";
    const MAP_TYPE_QQ = "QQ";

    public function getDateUri()
    {
        return Config::$jin_li_ming['url']."/GetDateServices.asmx/GetDate";
    }

    public function checkBm()
    {
        $data = unserialize($this->order->data);
        if ($data['client_name'] != "河南郑州百盛业务部"){
            throw new ApiException(201908261646, "你的业务部已停用此gps");
        }
    }

    public function addGps()
    {
        $this->checkOrder();
        $this->checkBm();
        return [
            'other_data' => [
                'success' => true,
                'msg' => '',
            ],
        ];
    }

    public function getGps()
    {
        $this->checkOrder();
        $this->checkBm();
        $last_info = $this->getLastLocationData();
        $other_data['gps_status'] = '未上线';
        $t = time()."000";
        if ($t - $last_info['heart_time']<1800*1000){
            $other_data['gps_status'] = '已上线';
        }
        return [
            'perfer_back' => $last_info,
            'order' => $this->order,
            'other_data' => $other_data,
        ];
    }

    public function getGpsLocationData()
    {
        $this->checkOrder();
        $this->checkBm();
        $last_info = $this->getLastLocationData();
        $data['url'] = self::getMapLocationByGaoDe($last_info['jingdu'], $last_info['weidu']);
        $data['html'] = '<script type="text/javascript">location.href = "'.$data['url'].'";</script>';
        return $data;
    }

    public function login()
    {
        $data = [
            'LoginName' => Config::$jin_li_ming['account'],
            'LoginPassword' => Config::$jin_li_ming['pwd'],
            'LoginType' => self::LOGIN_TYPE_COMPANY ,
            'language' => self::LANGUAGE_CN,
//            'lISMD5' => "", // Md5是否没加密[没加密,0;加密,1]
            'timeZone' => 8,
            'apply' => "APP",
//            'loginUrl' => Config::$jin_li_ming['url'],
//            'PushID' => "",
        ];
        $uri = Config::$jin_li_ming['url']."/GetDateServices.asmx/loginSystem";
        $client = new Client();
//        return $data;
        $response = $client->createRequest()
            ->setMethod('get')
            ->setUrl($uri)
            ->setData($data)
            ->send();
        $_r = $response->content;
        $_r = json_decode($_r);
        if ($_r&&$_r->errorCode!=200){
            throw new ErrorException("登录失败");
        }
        /**
         * "id": "d2b6d1ba-4bfe-4248-8428-ba0c8396ce86",
        "success": "true",
        "mds": "326df8019ee14852880551295ce3330b",
        "LoginType": "ENTERPRISE",
        "grade": 8,
        "msg": "登录成功",
        "errorCode": 200
         */
        return $_r;
    }

    public function getMds()
    {
        $x = $this->login();
        return $x->mds;
    }

    public function getLoginId()
    {
        $x = $this->login();
        return $x->id;
    }

    /**
     * 取设备列表
     * @return mixed|string
     * @throws ErrorException
     */
    public function getDevList()
    {
        $data = [
            'id' => $this->getLoginId(),
            'mds' => $this->getMds(),
            'method' => "getDeviceList",
            'pageCount' => 0,
        ];
        $uri = $this->getDateUri();
        $client = new Client();
//        return $data;
        $response = $client->createRequest()
            ->setMethod('get')
            ->setUrl($uri)
            ->setData($data)
            ->send();
        $_r = $response->content;
        $_r = json_decode($_r);
        if ($_r->errorCode!=200){
            throw new ErrorException("取设备列表异常".var_export($_r, true));
        }
        return $_r;
    }

    public function getDev()
    {
        $dev_list = $this->getDevList();
        $rows = ArrayHelper::toArray($dev_list->rows);
        $r = [];
        foreach ($rows as $k => $v){
            if ($v['macid'] == $this->order->gps_serial_number){
                $r = $v;
            }
        }
        return $r;
    }

    /**
     * 历史轨迹
     * @return mixed|string
     * @throws ErrorException
     */
    public function getHistoryTrajectory()
    {
        $data = [
            'mds' => $this->getMds(),
            'method' => "getHistoryMByMUtcNew",
//            'option' => "cn",
//            'school' => 1, // 登陆用户 ID
//            'custid' => 11, // 当前用户
//            'userID' => 111, // 设备 ID
            'macid' => "146020296185",
            'mapType' => "BAIDU", // 地图类型
//            'pwd' => "", // 设备密码
            'from' => (time()-86400)."000", // 历史轨迹结束时间(转成毫秒)
            'to' => time()."000", // 历史轨迹开始时间(转成毫秒)
//            'playLBS' => "",
        ];
        $uri = $this->getDateUri();
        $client = new Client();
//        return $data;
        $response = $client->createRequest()
            ->setMethod('get')
            ->setUrl($uri)
            ->setData($data)
            ->send();
        $_r = $response->content;
        $_r = json_decode($_r);
        if ($_r->errorCode!=200){
            throw new ErrorException("历史轨迹异常".var_export($_r, true));
        }
        return $_r;
    }

    /**
     * 最新位置）让用户通过ID在地图上跟综车辆
     */
    public function getLastLocation()
    {
        $data = [
            'id' => $this->getLoginId(),
            'mds' => $this->getMds(),
//            'method' => "getUserAndGpsInfoByIDsUtcNew",
            'method' => "GetGpsInfoByMacsUtc",
//            'option' => "cn",
//            'school' => 1, // 登陆用户 ID
//            'custid' => 11, // 当前用户
//            'userIDs' => 111, // 设备 ID
            'macids' => $this->order->gps_serial_number,
            'mapType' => "BAIDU", // 地图类型
//            't' => time(),  // 时间戳
        ];
        $uri = $this->getDateUri();
        $client = new Client();
//        return $data;
        $response = $client->createRequest()
            ->setMethod('get')
            ->setUrl($uri)
            ->setData($data)
            ->send();
        $_r = $response->content;
        $_r = json_decode($_r);
        if ($_r->errorCode!=200){
            throw new ErrorException("最新位置异常".var_export($_r. true));
        }
        return $_r;
    }

    public function getLastLocationData()
    {
        $last_info = $this->getLastLocation();
        $x = ArrayHelper::toArray($last_info);
        $data = $x['data'];
        $key = $data[0]['key'];
        if (!isset($data[0]['records'][0])){
            throw new ErrorException("没有records结果:".var_export($data, true));
        }
        $record = $data[0]['records'][0];
        $out = [];
        foreach ($key as $k => $v){
            $out[$k] = $record[$v];
        }
        return $out;
    }

    /**
     * 绑定设备到单位用户
     */
    public function bindDevAndUser()
    {
        $data = [
            'mds' => $this->getMds(),
            'method' => "ActiveAndAddDevice",
            'login_id' => $this->getLoginId(),
            'FullName' => "粤H25685", // 车牌号
            'Macid' => $this->order->gps_serial_number, // 设备号
        ];
        $uri = $this->getDateUri();
        $client = new Client();
//        return $data;
        $response = $client->createRequest()
            ->setMethod('get')
            ->setUrl($uri)
            ->setData($data)
            ->send();
        $_r = $response->content;
        $_r = json_decode($_r);
        if ($_r->errorCode!=200){
            throw new ErrorException("绑定设备到单位用户异常".var_export($_r, true));
        }
        return $_r;
    }
}